package com.lijiajian.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lijiajian.base.BaseService;
import com.lijiajian.dao.CustomerLossMapper;
import com.lijiajian.dao.CustomerMapper;
import com.lijiajian.dao.CustomerOrderMapper;
import com.lijiajian.pojo.CusDevPlan;
import com.lijiajian.pojo.Customer;
import com.lijiajian.pojo.CustomerLoss;
import com.lijiajian.pojo.CustomerOrder;
import com.lijiajian.query.CusDevPlanQuery;
import com.lijiajian.query.CustomerQuery;
import com.lijiajian.utils.AssertUtil;
import com.lijiajian.utils.PhoneUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@Service
public class CustomerService extends BaseService<Customer,Integer> {
    @Resource
    private CustomerMapper customerMapper;
    @Resource
    private CustomerOrderMapper customerOrderMapper;
    @Resource
    private CustomerLossMapper customerLossMapper;

    /**
     * 多条件查询客户数据
     * @param
     * @return
     */
    public Map<String,Object> queryCustomerByParams(CustomerQuery customerQuery){
        Map<String,Object> map=new HashMap<>();
        //开启分页
        PageHelper.startPage(customerQuery.getPage(),customerQuery.getLimit());
        PageInfo<Customer> pageInfo=new PageInfo<>(customerMapper.selectByParams(customerQuery));
        map.put("code",0);
        map.put("msg","success");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());

        return map;
    }

    /**
     * 添加客户
     * @param customer
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void addCustomer(Customer customer){
        /*参数校验*/
        checkCustomerParams(customer.getName(),customer.getFr(),customer.getPhone());
        //判断客户名的唯一性
        Customer temp=customerMapper.queryCustomerByName(customer.getName());
        AssertUtil.isTrue(null!=temp,"客户名称已存在，请重新输入");
        //设置参数默认值
        customer.setIsValid(1);
        customer.setState(0);
        customer.setCreateDate(new Date());
        customer.setUpdateDate(new Date());
        //客户编号
        String khno="KH"+System.currentTimeMillis();
        customer.setKhno(khno);
        //执行添加操作
        AssertUtil.isTrue(customerMapper.insertSelective(customer)!=1,"添加失败");

    }

    /**
     * 修改客户信息
     * @param customer
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateCustomer(Customer customer){
        /*参数校验*/
        AssertUtil.isTrue(null==customer.getId(),"待更新记录不存在");
        Customer temp = customerMapper.selectByPrimaryKey(customer.getId());
        AssertUtil.isTrue(null==temp,"待更新记录不存在");
        checkCustomerParams(customer.getName(),customer.getFr(),customer.getPhone());
        //判断客户名的唯一性
        temp=customerMapper.queryCustomerByName(customer.getName());
        AssertUtil.isTrue(null!=temp&&!temp.getId().equals(customer.getId()),"客户名称已存在，请重新输入");
        //设置参数默认值
        customer.setUpdateDate(new Date());
        //执行添加操作
        AssertUtil.isTrue(customerMapper.updateByPrimaryKeySelective(customer)!=1,"添加失败");

    }

    /**
     * 删除客户信息
     * @param ids
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteCustomer(Integer[] ids) {
        AssertUtil.isTrue(ids==null||ids.length==0,"待删除记录不存在");
        List<Customer> customerList=new ArrayList<>();
        for(Integer id:ids){
            Customer customer = customerMapper.selectByPrimaryKey(id);
            AssertUtil.isTrue(null==customer,"待删除记录不存在");
            customer.setIsValid(0);
            customer.setUpdateDate(new Date());
            customerList.add(customer);
        }
        AssertUtil.isTrue(customerMapper.updateBatch(customerList)!=ids.length,"删除记录失败");

    }

    /**
     * 更新客户流失状态
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateCustomerState(){
        //查询流失的客户数据
        List<Customer> lossCustomerList=customerMapper.queryLossCustomer();
        //将流失的客户数据批量添加到客户流失表中
        if(lossCustomerList!=null&&lossCustomerList.size()>0){
            //接受流失的客户id
            List<Integer> lossCustomerIds=new ArrayList<>();
            //定义流失客户的列表
            List<CustomerLoss> customerLossList=new ArrayList<>();
            for(Customer customer:lossCustomerList){
                CustomerLoss customerLoss = new CustomerLoss();
                customerLoss.setCreateDate(new Date());
                customerLoss.setCusManager(customer.getCusManager());
                customerLoss.setCusName(customer.getName());
                customerLoss.setCusNo(customer.getKhno());
                customerLoss.setIsValid(1);
                customerLoss.setUpdateDate(new Date());
                //0暂缓流失，1确认流失
                customerLoss.setState(0);
                //客户最后下单时间
                CustomerOrder customerOrder=customerOrderMapper.queryLossCustomerOrderByCustomerId(customer.getId());
                if(customerOrder!=null){

                    customerLoss.setLastOrderTime(customerOrder.getOrderDate());
                }
                customerLossList.add(customerLoss);
                lossCustomerIds.add(customer.getId());
            }
            //批量添加客户流失记录
            AssertUtil.isTrue(customerLossMapper.insertBatch(customerLossList)!=customerLossList.size(),"添加失败");
            //批量更新客户的流失状态
            AssertUtil.isTrue(customerMapper.updateCustomerStateByIds(lossCustomerIds)!=lossCustomerIds.size(),"更新失败");
        }


    }

    /**
     * 查询客户贡献
     * @param customerQuery
     * @return
     */
    public Map<String,Object> queryCustomerContribution(CustomerQuery customerQuery){
        Map<String,Object> map=new HashMap<>();
        //开启分页
        PageHelper.startPage(customerQuery.getPage(),customerQuery.getLimit());
        PageInfo<Map<String,Object>> pageInfo=new PageInfo<>(customerMapper.queryCustomerContributionByParams(customerQuery));
        map.put("code",0);
        map.put("msg","success");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());

        return map;

    }

    /**
     * 查询客户构成
     * @return
     */
    public Map<String,Object> countCustomerMake(){
        Map<String,Object> map=new HashMap<>();
        //客户构成数据列表
        List<Map<String, Object>> dataList = customerMapper.countCustomerMake();
        //x轴数据
        List<String> data1=new ArrayList<>();
        //y轴数据
        List<Integer> data2=new ArrayList<>();
        dataList.forEach(m->{
            data1.add(m.get("level").toString());
            data2.add(Integer.parseInt(m.get("total").toString()));
        });
        map.put("data1",data1);
        map.put("data2",data2);
        return map;

    }
    /**
     * 查询客户构成
     * @return
     */
    public List<Map<String,Object>> countCustomerMake02(){
        List<Map<String,Object>> maplist=new ArrayList<>();
        //客户构成数据列表
        List<Map<String, Object>> dataList = customerMapper.countCustomerMake();

        dataList.forEach(m->{
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("name",m.get("level"));
            dataMap.put("value",m.get("total"));
            maplist.add(dataMap);

        });

        return maplist;

    }
    private void checkCustomerParams(String name, String fr, String phone) {
        AssertUtil.isTrue(null==name,"客户名称不能为空");
        AssertUtil.isTrue(null==fr,"法人不能为空");
        AssertUtil.isTrue(null==phone,"手机号码不能为空");
        AssertUtil.isTrue(!PhoneUtil.isMobile(phone),"手机号码格式不正确");
    }
}
